// 判断文件类型
function isImageType(file) {
  var types = /^image\/(jpeg|png|gif|bmp)$/;
  return types.test(file.type);
}

// 控制图片按比例缩放并不超过一定宽度和高度
function DrawImage(ImgD, maxwidth, maxheight) {
  var image = new Image();
  image.src = ImgD.src;
  var width = image.width;
  var height = image.height;
  if(width <= maxwidth && height <= maxheight) {
    return;
  }
  if(width > maxwidth && height <= maxheight) {
    ImgD.width = maxwidth;
    ImgD.height = maxwidth / width * height;
    return;
  }
  if(width <= maxwidth && height > maxheight) {
    ImgD.width = maxheight / height * width;
    ImgD.height = maxheight;
    return;
  }
  if (height / width >= maxheight / maxwidth) {
    ImgD.width = maxheight / height * width;
    ImgD.height = maxheight;
  } else {
    ImgD.width = maxwidth;
    ImgD.height = maxwidth / width * height;
  }
}

function fileSizeFormat(size, level) {
  var units = ['B', 'K', 'M', 'G', 'T'];
  
  if(!level) {
    level = 0;
  }else if(level > 4) {
    return Math.ceil(size * 1024) + units[4];
  }
  
  if(size < 1024) {
    return Math.ceil(size) + units[level];
  }
  
  size = size / 1024;
  level = level + 1;
  return fileSizeFormat(size, level);
}

var websocket = null;
var domain = location.hostname + ":" + location.port;
var full_domain = 'http://' + domain;
var upload_url = 'http://localhost/lua/upload';
var download_url = 'http://localhost/storage';

function createWebSocket() {
  if ('WebSocket' in window) {
    websocket = new WebSocket("ws://" + domain + "/websocket");
  } else if ('MozWebSocket' in window) {
    websocket = new MozWebSocket("ws://" + domain + "/websocket");
  } else {
    websocket = new SockJS("http://" + domain + "/websocket/sockjs");
  }

  websocket.onopen = function(event) {
    $('#send').removeAttr('disabled')
    console.log("open: connect success!")
  };

  websocket.onmessage = function onMessage(event) {
    renderMessage(JSON.parse(event.data));
  };

  websocket.onerror = function(event) {
    console.log("error: " + event.reason)
  };

  websocket.onclose = function(event) {
    $('#send').attr('disabled', 'disabled')
    console.log("close: " + event.reason)
  };
}

function handleMessage(data) {
  console.log(data);
  if (data.type == 'TEXT') {
    var container = $('<div class="content-row"/>').html(data.msg).appendTo('#shown');
    if (data.speaker) {
      container.addClass('left');
      $('<span/>').html(data.speaker).prependTo(container);
    } else {
      container.addClass('right');
      $('<span/>').html(window.CURRENT_USER.realname).appendTo(container);
    }
  }
}

function renderMessage(data) {
  console.log(data)
  var template;
  var isremote = data.speaker ? 'left' : 'right';
  var speaker = data.speaker || window.CURRENT_USER.realname;
  var content = data.content;
  if (data.type == 'TEXT') {
    template = `
      <div class="content-row ${isremote}">
        <span class="speaker">${speaker}</span>
        <div class="text">
          ${content}
        </div>
      </div>
    `;
  } else if (data.type == 'BINARY') {
    if(content.is_image) {
      template = `
        <div class="content-row ${isremote}">
          <span class="speaker">${speaker}</span>
          <img class="image" src="${download_url}${content.url}" 
            alt="${content.file_name}" onload="DrawImage(this,150,90)"/>
        </div>
      `;
    } else {
      template = `
        <div class="content-row ${isremote}">
          <span class="speaker">${speaker}</span>
          <div class="file right">
            <img src="./images/file.png" />
            <span class="name">${content.file_name}</span><br>
            <span class="size">${fileSizeFormat(content.size)}</span>
            <div class="operate">
              <a href="${download_url}${content.url}?filename=${content.file_name}">下载</a>
            </div>
          </div>
        </div>
      `;
    }
  }
  $('#shown').append(template);
}

function sendMessage() {
  if (websocket.readyState == websocket.OPEN) {
    var content = $('#editor').html();
    if (content != '') {
      var obj = {content: content, type: "TEXT"};
      renderMessage(obj);
      websocket.send(JSON.stringify(obj));
      $('#editor').html('');
    }
  }
}

function uploadFile() {
  $.upload({
    url : upload_url,
    redirect : full_domain + '/file/upload/success',
    data : {'name': '张三'},
    success: function(data) {
      $.each(data.data, function() {
        var obj = {content: this, type: "BINARY"};
        renderMessage(obj);
        websocket.send(JSON.stringify(obj));
      });
    }
  });
}

$(function() {

  $('#current_username').html(window.CURRENT_USER.realname);

  createWebSocket();
});